package com.maimang.platform.crm.service.impl;

import com.maimang.platform.common.utils.DateUtils;
import com.maimang.platform.crm.entity.CrmCustomer;
import com.maimang.platform.crm.mapper.CrmCustomerMapper;
import com.maimang.platform.crm.service.CustomerService;
import com.maimang.platform.exception.BusinessException;
import com.maimang.platform.lang.ConvertUtils;
import com.maimang.platform.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Rocky
 * @version 1.0.0
 * @classname CustomerServiceImpl
 * @description <br>客户清单服务层实现类</br>
 * @date 2019-09-23 15:42:23
 * @email jintaozhao@qq.com
 */
@Service
public class CustomerServiceImpl implements CustomerService {

	private static final Logger log = LoggerFactory.getLogger(CustomerServiceImpl.class);

	@Autowired
	private CrmCustomerMapper customerMapper;

	/**
	 * 查询客户清单信息
	 *
	 * @param customerId 客户清单ID
	 * @return 客户清单信息
	 */
	@Override
	public CrmCustomer selectCustomerById(Integer customerId) {
		return customerMapper.selectCrmCustomerById(customerId);
	}

	/**
	 * 查询客户清单列表
	 *
	 * @param customer 客户清单信息
	 * @return 客户清单集合
	 */
	@Override
	public Map<String, List<CrmCustomer>> selectCustomerMap(CrmCustomer customer) {
		List<CrmCustomer> customerList = customerMapper.selectCrmCustomerList(customer);
		Map<String, List<CrmCustomer>> map = new HashMap<>();
		for (CrmCustomer crmCustomer : customerList) {
			map.computeIfAbsent(crmCustomer.groupKey(), k -> new ArrayList<>()).add(crmCustomer);
		}
		return map;
	}

	/**
	 * 查询客户清单列表
	 *
	 * @param customer 客户清单信息
	 * @return 客户清单集合
	 */
	@Override
	public List<CrmCustomer> selectCustomerList(CrmCustomer customer) {
		return customerMapper.selectCrmCustomerList(customer);
	}

	/**
	 * 根据集团及公司名称查询客户信息
	 *
	 * @param groupName   集团名称
	 * @param companyName 公司名称
	 * @param userName    销售名称
	 * @return
	 */
	@Override
	public CrmCustomer selectCustomerByName(String groupName, String companyName, String userName) {
		List<CrmCustomer> customers = customerMapper.selectCustomerByName(groupName, companyName, userName);
		if (customers.size() > 0)
			return customers.get(0);
		return null;
	}

	/**
	 * 新增客户清单
	 *
	 * @param customer 客户清单信息
	 * @return 结果
	 */
	@Override
	public int insertCustomer(CrmCustomer customer) {
		return customerMapper.insertCrmCustomer(customer);
	}

	/**
	 * 修改客户清单
	 *
	 * @param customer 客户清单信息
	 * @return 结果
	 */
	@Override
	public int updateCustomer(CrmCustomer customer) {
		return customerMapper.updateCrmCustomer(customer);
	}

	/**
	 * 删除客户清单对象
	 *
	 * @param ids 需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteCustomerByIds(String ids) {
		return customerMapper.deleteCrmCustomerByIds(ConvertUtils.toStrArray(ids));
	}

	/**
	 * 导入客户数据
	 *
	 * @param customerList    客户数据列表
	 * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
	 * @param operName        操作用户
	 * @return 结果
	 */
	@Override
	public String importCustomer(List<CrmCustomer> customerList, Boolean isUpdateSupport, String operName) {
		if (StringUtils.isNull(customerList) || customerList.size() == 0) {
			throw new BusinessException("导入客户数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		for (CrmCustomer customer : customerList) {
			try {
				// 验证是否存在这个客户
				CrmCustomer c = this.selectCustomerByName(customer.getGroupName(), customer.getCompanyName(), customer.getUserName());
				if (StringUtils.isNull(c)) {
					customer.setCreateUser(operName);
					customer.setCreateTime(DateUtils.getNowDate());
					if (customer.getIsNew().equalsIgnoreCase("新客户"))
						customer.setIsCooperated("未合作");
					else if (customer.getIsNew().equalsIgnoreCase("老客户"))
						customer.setIsCooperated("已合作");
					customerMapper.insertCrmCustomer(customer);
					successNum++;
					successMsg.append("<br/>" + successNum + "、客户[ " + customer.getCompanyName() + " ]导入成功");
				} else if (isUpdateSupport) {
					customer.setUpdateUser(operName);
					customer.setUpdateTime(DateUtils.getNowDate());
					customer.setCustomerId(c.getCustomerId());
					if (customer.getIsNew().equalsIgnoreCase("新客户"))
						customer.setIsCooperated("未合作");
					else if (customer.getIsNew().equalsIgnoreCase("老客户"))
						customer.setIsCooperated("已合作");
					customerMapper.updateCrmCustomer(customer);
					successNum++;
					successMsg.append("<br/>" + successNum + "、客户[ " + customer.getCompanyName() + " ]更新成功");
				} else {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、客户[ " + customer.getCompanyName() + " ]已存在");
				}
			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、客户[ " + customer.getCompanyName() + " ]导入失败：";
				failureMsg.append(msg + e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new BusinessException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}

}
